/*
 * XQueryDocument.java
 */

package xq.swing.text;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.StyledEditorKit;

/**
 *
 * @author ThorntonRP
 */
public class XQueryDocument extends DefaultStyledDocument {

	private static final long serialVersionUID = 4847057153191637496L;
	
	private Element root;

	public XQueryDocument() {
		root = getDefaultRootElement();
		putProperty(DefaultEditorKit.EndOfLineStringProperty, "\n");
	}
	
	@Override
	public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
		super.insertString(offset, str, a);
		updateSyntaxHighlighting(offset, str.length());
	}

	@Override
	public void remove(int offset, int length) throws BadLocationException {
		super.remove(offset, length);
		updateSyntaxHighlighting(offset, 0);
	}

	private void updateSyntaxHighlighting(int offset, int length) throws BadLocationException {
		String text = getText(0, getLength());
		
		int firstModifiedLine = root.getElementIndex(offset);
		int lastModifiedLine   = root.getElementIndex(offset + length);
		
		for (int line = firstModifiedLine; line <= lastModifiedLine; line++) {
			highlight(text, line);
		}
		System.out.println("'"+text+"'");
	}
	
	private void highlight(String text, int line) {
		int startOffset = root.getElement(line).getStartOffset();
		int endOffset = root.getElement(line).getEndOffset() - 1;
	}

	private static class XQueryEditorKit extends StyledEditorKit {

		public static final String XQUERY_CONTENT_TYPE = "text/xquery";
		
		private static final long serialVersionUID = -7348739062909779552L;

		@Override
		public Document createDefaultDocument() {
			return new XQueryDocument();
		}

		@Override
		public String getContentType() {
			return XQUERY_CONTENT_TYPE;
		}
	}
/*
	public static void main(String a[]) {
		String mimeType = XQueryEditorKit.XQUERY_CONTENT_TYPE;
		XQueryEditorKit editorKit = new XQueryEditorKit();
		JTextPane editor = new JTextPane();
		editor.setFont(new Font("Monospaced", Font.PLAIN, 13));
		editor.setEditorKitForContentType(editorKit.getContentType(), editorKit);
		editor.setContentType(mimeType);
		
		JFrame f = new JFrame("XQuery Syntax Highlighting");
		f.setLayout(new BorderLayout());
		f.add(new JScrollPane(editor), BorderLayout.CENTER);
		f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		f.setSize(800, 600);
		f.setVisible(true);
	}
*/
}
